import { Tabs, message } from 'antd'
import React, { useEffect, useState } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
// import PropType from 'prop-types'
import './index.less'
import { useSelector } from 'react-redux'
import { getDelPath } from '@/store/getters'
import { store } from '@/store'
import { TabsList } from '@/model/route'
import { setDelPath } from '@/store/action'
interface TabsContainerProps
  extends React.HTMLAttributes<HTMLElement> {
  isSmall: boolean
  tabsList: TabsList[]
  setTabsList: Function
}

const TabsContainer = (props: TabsContainerProps) => {
  const { isSmall, tabsList, setTabsList } = props
  const { pathname } = useLocation()
  const navigate = useNavigate()
  const [activeValue, setActiveValue] =
    useState<string>(pathname)
  const delPath = useSelector(getDelPath)
  const clickTabs = (path: string) => {
    console.log('tabsList', tabsList)
    console.log('path', path)

    const result = tabsList.find(
      (item) => item.path === path
    ) as TabsList
    navigate(
      result.search
        ? `${result.path}${result.search}`
        : `${result.path}`
    )
  }
  useEffect(() => {
    setActiveValue(pathname)
  }, [pathname])
  useEffect(() => {
    if (delPath) {
      delTabs(delPath)
      if (delPath) {
        store.dispatch(setDelPath(''))
      }
    }
  }, [delPath])
  useEffect(() => {
    setTimeout(() => {
      if (
        tabsList.find((item) => item.path === pathname)
          ?.title
      ) {
        document.title = tabsList.find(
          (item) => item.path === pathname
        )?.title as string
      }
    }, 100)
  }, [pathname, tabsList])
  const delTabs = (tabPath?: string) => {
    console.log('tabPath', tabPath)
    console.log('tabsList', tabsList)
    if (pathname === tabPath) {
      tabsList.forEach((item, index) => {
        if (item.path !== tabPath) return
        const nextTab =
          tabsList[index + 1] || tabsList[index - 1]
        if (!nextTab) return
        navigate(nextTab.path as string)
      })
    }
    if (tabsList.length > 1) {
      setTabsList(
        tabsList.filter((item) => item.path !== tabPath)
      )
    } else {
      message.warn('这是最后一页，不能再关闭了')
    }
  }
  return (
    <div className="tabs">
      <Tabs
        activeKey={activeValue}
        onChange={clickTabs}
        hideAdd
        type="editable-card"
        onEdit={(path) => {
          delTabs(path as string)
        }}
        items={tabsList}
      />
    </div>
  )
}

// TabsContainer.propTypes = {
//   isSmall:PropType.bool.isRequired,
//   tabsList:PropType.array.isRequired,
//   setTabsList:PropType.func.isRequired
// }

export default TabsContainer
